<template>
  <div class="mainsu">
    <div class="main_spac1">
      <div class="main_white padding10 paddingBottom20">
        <div class="mainor_form">
          <div class="mainor_te">
            <el-button type="primary" @click="addDiaVisible = true"
              >新增商品</el-button
            >
            <router-link to="/marketing/points/record">
              <el-button>兑换记录</el-button></router-link
            >
          </div>
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="70px"
          >
            <el-form-item label="商品名称" prop="goods_spu_id">
              <undercarriage
                class="wid220"
                ref="changeGoodsInput"
                @clear="
                  () => {
                    this.form.goods_spu_id = '';
                  }
                "
                @sendValue="
                  (data) => {
                    this.form.goods_spu_id = data.id;
                  }
                "
              ></undercarriage>
            </el-form-item>
            <el-form-item label="活动状态" prop="status">
              <el-select
                v-model.trim="form.status"
                placeholder="活动状态"
                class="wid220"
              >
                <el-option label="所有" :value="parseInt(0)"></el-option>
                <el-option
                  v-for="(item, index) in status_list"
                  :key="index"
                  :label="item"
                  :value="parseInt(index) + 1"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                class="reset marginLeft10"
                type="primary"
                @click="reset"
                >重置</el-button
              >
              <el-button
                type="primary"
                @click="getArticleList"
                :loading="listLoading"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="main_table marginTop10" style="min-height: 550px">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            :header-cell-class-name="this.$verticaline"
          >
            <el-table-column label="序号" align="center" width="80">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              label="商品图片"
              min-width="120"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <div class="demo-image__error mainor_im">
                  <el-image
                    fit="fill"
                    :src="scope.row.goods_img"
                    :preview-src-list="scope.row.pics"
                  >
                    <div slot="error" class="image-slot">
                      <img :src="puzzleImg" />
                    </div>
                  </el-image>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="商品名称"
              align="center"
              prop="goods_name"
              show-overflow-tooltip
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              label="单位"
              align="center"
              prop="goods_spu_unit"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              label="市场价"
              align="center"
              prop="goods_spu_market_price"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              label="积分"
              align="center"
              prop="points"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              label="兑换库存"
              align="center"
              prop="inventory"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              label="剩余库存"
              align="center"
              prop="inventory_surplus"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              label="单次兑换限制"
              align="center"
              prop="once_limit"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              label="订单金额限制"
              align="center"
              prop="order_money_limit"
              show-overflow-tooltip
              min-width="120"
            />
            <el-table-column
              label="状态"
              align="center"
              prop="order_money_limit"
              show-overflow-tooltip
              min-width="120"
            >
              <template slot-scope="scope">
                <span :class="'status' + scope.row.status">{{
                  status_list[scope.row.status]
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              align="center"
              prop="name"
              show-overflow-tooltip
              min-width="160"
            >
              <template slot-scope="scope">
                {{ parseTime(Number(scope.row.created_at)) }}
              </template>
            </el-table-column>
            <el-table-column
              label="管理操作"
              align="center"
              fixed="right"
              width="260"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <el-link
                  type="danger"
                  v-if="scope.row.status != 0"
                  @click="changeStatus(scope, 1)"
                  >暂停</el-link
                >
                <el-link
                  type="success"
                  v-if="scope.row.status == 0"
                  @click="changeStatus(scope, 2)"
                  >开始</el-link
                >
                <el-link type="info" @click="handleAdjust(scope.row)"
                  >调整库存</el-link
                >
                <el-link type="danger" @click="handleClose(scope.row)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <el-pagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>

        <!-- 新增商品 -->
        <el-dialog
          title="新增商品"
          class="main_dialog dialog1000"
          :visible.sync="addDiaVisible"
          @closed="closeDia"
        >
          <div class="mainor_form">
            <el-form
              :inline="true"
              :model="grant_form"
              class="demo-form-inline"
              ref="diaRefForm"
              label-width="70px"
              style="width: 100%"
            >
              <el-form-item label="商品名称" prop="uid">
                <undercarriage
                  class="wid220"
                  ref="changeGoodsInput_dialog"
                  @sendValue="getGoods"
                ></undercarriage>
              </el-form-item>

              <!-- <el-form-item>
                <el-button class="reset marginLeft10">重置</el-button>
                <el-button type="primary" :loading="dia_listLoading"
                  >搜索</el-button
                >
              </el-form-item> -->
            </el-form>
          </div>
          <div class="main_table">
            <el-table
              ref="multipleTable"
              v-loading="dia_listLoading"
              :data="goods_list"
              element-loading-text="加载中"
              fit
              border
              highlight-current-row
              :header-cell-class-name="this.$verticaline"
            >
              <!-- <el-table-column :render-header="renderheader" width="50">
                <template slot-scope="scope">
                  <el-checkbox
                    v-model="scope.row.checked"
                    @change="(val) => oneChange(val, scope.row)"
                  ></el-checkbox>
                </template>
              </el-table-column> -->
              <el-table-column
                label="商品名称"
                align="center"
                prop="goods_name"
                show-overflow-tooltip
                min-width="120"
              />
              <el-table-column
                label="积分"
                align="center"
                prop="points"
                show-overflow-tooltip
                min-width="120"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.points"
                    :min="1"
                    :precision="0"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                label="兑换库存"
                align="center"
                prop="inventory"
                show-overflow-tooltip
                min-width="120"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.inventory"
                    :min="1"
                    :precision="2"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                label="单次兑换限制"
                align="center"
                prop="once_limit"
                show-overflow-tooltip
                min-width="120"
                :render-header="(h, obj) => renderHeader_purchase(h, obj, 3)"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.once_limit"
                    :min="0"
                    :precision="2"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                label="订单金额限制"
                align="center"
                prop="order_money_limit"
                show-overflow-tooltip
                min-width="120"
                :render-header="(h, obj) => renderHeader_purchase(h, obj, 4)"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.order_money_limit"
                    :min="0"
                    :precision="2"
                    :controls="false"
                  ></el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                label="管理操作"
                align="center"
                show-overflow-tooltip
                min-width="120"
              >
                <template slot-scope="scope">
                  <el-link type="danger" @click="handleDelete(scope.$index)"
                    >删除</el-link
                  >
                </template></el-table-column
              >
            </el-table>
          </div>

          <div slot="footer">
            <el-button @click="addDiaVisible = false">取 消</el-button>
            <el-button
              type="primary"
              :disabled="goods_list.length > 0 ? false : true"
              @click="handleSave"
              v-repeatClick
              >保存</el-button
            >
          </div>
        </el-dialog>
        <!-- 调整库存 -->
        <el-dialog
          title="调整库存"
          :visible.sync="adjustDiaVisible"
          @closed="closeDia"
          width="500px"
        >
          <div class="adjustContainer">
            <div>
              <li><span>商品名称：</span>{{ adjust_goods.goods_name }}</li>
              <li>
                <span>剩余库存：</span>{{ adjust_goods.inventory_surplus }}
              </li>
              <li>
                <span>兑换库存：</span>
                <el-input-number
                  size="medium"
                  v-model="adjust_goods.inventory"
                  :min="0"
                  :precision="2"
                ></el-input-number>
              </li>
            </div>
          </div>
          <div slot="footer">
            <el-button @click="adjustDiaVisible = false">取 消</el-button>
            <el-button type="primary" @click="adjustSave" v-repeatClick
              >保存</el-button
            >
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  get_point_index,
  get_point_add,
  get_point_changeStatus,
  get_point_delete,
  get_point_edit,
} from "@/api/marketing/marketing_points.js";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime } from "@/utils/index";
import { puzzleImg } from "@/api/currency";
import undercarriage from "./components/undercarriage.vue";

export default {
  computed: {
    ...mapGetters(["avatar"]),
  },
  components: {
    undercarriage,
  },
  data() {
    return {
      // 时间
      parseTime,
      puzzleImg,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,

      // 列表数据
      list: [],
      status_list: [],
      type_list: {},
      listLoading: false,
      // 搜索
      form: {
        type: null,
        status: null,
        goods_spu_id: "",
      },
      // 全选
      selectArr: [],
      // 新增商品
      addDiaVisible: false,
      grant_form: {
        uid: "",
      },
      goods_list: [],
      checkAll: false,
      // 发放优惠券分页
      grant_current: {
        page: 1,
        per_page: 20,
      },
      dia_listLoading: false,
      // 全选
      selectArr: [],
      grant_limit: 20,
      grant_totalCount: 1,
      // 调整库存
      adjustDiaVisible: false,
      adjust_goods: {
        inventory: 0,
        goods_name: "",
        id: "",
        inventory_surplus: "",
      },
    };
  },
  created() {
    // 列表
    this.get_point_index();
  },
  methods: {
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.get_point_index();
    },
    // 重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.$refs["changeGoodsInput"].name = "";
      this.get_point_index();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.get_point_index();
    },
    changePage(page) {
      this.current.page = page;
      this.get_point_index();
    },
    // 列表
    get_point_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      get_point_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.status_list = res.data.status_list;
          res.data.list.data.map((e) => {
            e.goods_name = "";
            e.goods_spu_unit = "";
            e.goods_spu_market_price = "";
            e.goods_img = "";
            e.pics = [];
            let arr = [];
            if (e.goods) {
              e.goods_name = e.goods.name;
              if (e.goods.images.length > 0) {
                e.goods_img = this.avatar.domain + e.goods.images[0].path;
                e.goods.images.map((p) => {
                  let a = this.avatar.domain + p.path;
                  arr.push(a);
                });
                e.pics = arr;
              }
            }
            if (e.goods_spu) {
              e.goods_name += `【${e.goods_spu.spu_unit.title}】`;
              e.goods_spu_unit = e.goods_spu.spu_unit.title;
              e.goods_spu_market_price = e.goods_spu.market_price;
            }
          });
          this.list = res.data.list.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      return form;
    },
    // 关闭
    handleClose(row) {
      let id = row.id;

      this.$confirm(
        "活动关闭后无法恢复, 已参与活动的订单不受影响，确认关闭?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let data = Object.assign(
            {
              sign: Md5(
                objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
              ),
            },
            apiUrl().name,
            { id: id }
          );
          get_point_delete(data).then((res) => {
            if (res.errcode == 0) {
              this.$message.success("删除成功");
              this.get_point_index();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 调整库存
    handleAdjust(row) {
      let status = row.status;
      if (status == 1) {
        this.$message.warning("调整库存需要先将商品暂停");
        return;
      } else {
        this.adjust_goods.inventory = row.inventory;
        this.adjust_goods.goods_name = row.goods_name;
        this.adjust_goods.id = row.id;
        this.adjust_goods.inventory_surplus = row.inventory_surplus;
        this.adjustDiaVisible = true;
      }
    },
    adjustSave() {
      if (this.adjust_goods.inventory == 0) {
        this.$message.error("库存数量需大于0");
        return;
      }

      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {
          id: this.adjust_goods.id,
          inventory: this.adjust_goods.inventory,
        }
      );
      get_point_edit(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("调整成功");
          this.get_point_index();
          this.adjustDiaVisible = false;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 修改状态
    changeStatus(scope, type) {
      console.log(scope.row);
      let row = scope.row;

      switch (type) {
        case 1:
          this.$confirm(`确定暂停【${row.goods_name}】的兑换?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              let form = {
                id: row.id,
                status: 0,
              };
              this.get_point_changeStatus(form);
            })
            .catch(() => {});
          break;
        case 2:
          this.$confirm(`确定开始【${row.goods_name}】`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              console.log(234423432);
              let form = {
                id: row.id,
                status: 1,
              };
              this.get_point_changeStatus(form);
            })
            .catch(() => {});
          break;
      }
    },
    get_point_changeStatus(form) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      console.log(form);
      get_point_changeStatus(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("状态修改成功");
          this.get_point_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 选择全部
    changeAll(val) {
      this.checkAll = val;
      // 全选反选
      this.user_list.map((e) => {
        e.checked = val;
      });
    },
    // 一级选择
    oneChange(val, row) {
      row.checked = val;
    },
    renderheader(h, { column, $index }) {
      return h("el-checkbox", {
        // 表示属性
        attrs: {
          effect: "dark",
        },
        props: {
          value: this.checkAll,
        },
        on: {
          change: (val) => {
            this.changeAll(val);
          },
        },
      });
    },
    // 表头注释
    renderHeader_purchase(h, { column, $index }, type) {
      let content = "";
      switch (type) {
        case 3:
          content = "注释：单次最大兑换数量，0表示不限制";
          break;
        case 4:
          content =
            "注释：下单金额必须大于等于设置值，才能兑换商品，0表示不限制";
          break;
      }
      return h("div", [
        h("span", {
          domProps: {
            innerHTML: column.label,
          },
        }),
        h(
          "el-tooltip",
          {
            attrs: {
              effect: "dark",
              content: content,
              placement: "top",
            },
          },
          [
            h("i", {
              style: "margin-left: 5px;margin-top:-1px;",
              class: "el-icon-question table-msg",
            }),
          ]
        ),
      ]);
    },
    handleDelete(index) {
      this.goods_list.splice(index, 1);
    },
    // 获取商品
    getGoods(res) {
      let obj = {
        goods_name: `${res.goods.name}【${res.spu_name.title}】`,
        goods_id: res.goods_id,
        goods_spu_id: res.id,
        points: 0,
        inventory: 0,
        once_limit: 0,
        order_money_limit: 0,
        checked: false,
      };
      let flag = false;
      this.goods_list.map((e) => {
        if (e.goods_id == obj.goods_id && e.goods_spu_id == obj.goods_spu_id) {
          flag = true;
        }
      });
      if (!flag) {
        this.goods_list.push(obj);
      }
    },
    // 保存
    handleSave() {
      let goods_list = JSON.parse(JSON.stringify(this.goods_list));
      let list = goods_list.map((e) => {
        let { checked, goods_name, ...sz } = e;
        return { ...sz };
      });
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { list: JSON.stringify(list) }
      );
      get_point_add(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("添加成功");
          this.get_point_index();
          this.addDiaVisible = false;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 关闭弹窗
    closeDia() {
      this.goods_list = [];
      if (this.$refs["changeGoodsInput_dialog"]) {
        this.$refs["changeGoodsInput_dialog"].name = "";
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.mainsu {
  .mainor_form form {
    width: calc(100% - 120px);
  }
  .main_num {
    .mainsu_te {
      position: relative;
      top: -1px;
    }
  }
}
/deep/.el-progress-bar__innerText {
  transform: translateY(-1px);
}
.main_dialog {
  .main_table {
    /deep/.el-table__body-wrapper {
      overflow-y: auto;
      height: 400px;
    }
  }
  .main_xq ul li {
    width: 33.33%;
    margin-top: 5px;
    margin-bottom: 5px;
  }
  .progress_list {
    margin-top: 10px;
    p {
      height: 24px;
      line-height: 24px;
    }
    .progress_list_red {
      color: red;
    }
    .progress_list_su {
      color: #03a98e;
    }
  }
}

.type1 {
  color: #03a98e;
}
.type2 {
  color: #aacd6e;
}

.status0 {
  color: #cccccc;
}
.status1 {
  color: #03a98e;
}
.status2 {
  color: #f56c6c;
}

/deep/ .main_table .el-table--small td .cell {
  height: auto;
  white-space: normal !important;
  p {
    margin: 0 5px;
    background-color: #f0f9eb;
    color: #67c23a;
    padding: 2px 0;
  }
  .goods_data_span {
    background-color: #fef0f0;
    color: #f56c6c;
    padding: 2px;
    margin-right: 2px;
    margin-bottom: 5px;
    display: inline-block;
  }
}
.main_dialog /deep/ .el-checkbox {
  margin-bottom: 0;
}
.adjustContainer {
  padding: 0 20px;
  font-size: 16px;

  li {
    margin-bottom: 25px;
  }
}
</style>
